'''
Created on 28/01/2013

@author: Ethan
'''
from MaltegoTransform import *
import os
import math
from ToMaltego import add_paper
from BibTeXParser import  BibTeXParser


'''Variables'''
transform = MaltegoTransform()
parser = BibTeXParser()


'''Environment Settings'''
#Change this to local bib file location
bibtexfile = "C:\\Users\\Ethan\\Eclipse\\bibtex-to-maltego\\test.bib" 
#Grabs the Name of the author from Maltego
name = str(sys.argv[1])


'''Helper Functions'''
def find(f, seq):
    k = -1
    for item in seq:
        k = k+1
        if f == item: 
            return k
    return 0

def is_bibtexfile(filecheck):
    return filecheck.endswith(".bib")

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False


'''Main Transformation'''
def do_transformation():
    transform.addUIMessage("Paper transformation from Mendelay beginning.")
    
    #For each record in the bibTeX file
    count = 0
    while count < len(results):
        #Get the next record                                
        biblography = results[count]
        #Get the Authors from the record                  
        namecheck = biblography['author']
        #If the Author entity is within the Record        
        if name in namecheck:    
            #Grab the Title of the Record                               
            titles = biblography['title']
            #Set Default Citation Weight
            cite = 100
            #If Keywords in Record
            if "keywords" in biblography:
                #Set variables for counter, citations
                i = 0
                citations = 0
                #Split the Keywords array
                keywords = biblography['keywords'].split(",")
                #Search through the array
                while i < len(keywords):
                    #Find a number
                    if is_number(keywords[i]):
                        #Set Citations as the found number (Citations will be the only number)
                        citations = float(keywords[i])
                    #Next array entry
                    i = i + 1
                #If Citations > 0 (And not N)
                if citations > 0:
                    #Calculate a weight based on Log(C)*100 + 100
                    cite = int((math.log10(citations)*100) + 100)
            #Provide a notification of the Title                    
            transform.addUIMessage(str(titles))
            #Add the Paper to Maltego with Citation Weight                 
            add_paper(transform, str(titles), cite)                   
        count = count + 1

    transform.addUIMessage("Paper transformation from Mendelay completed!")


'''Main Program'''
#Ensure file specified is valid and .bib
if os.path.isfile(bibtexfile) and is_bibtexfile(bibtexfile):
    #Start main code   
    try: 
        #Get all the data from the .bib                                                       
        results = parser.parse(bibtexfile)
        #Run the transformation
        do_transformation()
    #Catch any file parsing errors                                   
    except IOError as e:
        #Print error                            
        transform.addUIMessage("File parsing error: "+ e)
#If file validation or .bib fails      
else:
    #Print failure notification
    transform.addUIMessage("File not valid")

#Print Transformation Log
transform.returnOutput()
